#pragma once

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<mutex>
#include<cassert>
#include<fstream>
#include<jsoncpp/json/json.h>

#include"../comm/log.hpp"
#include"../comm/util.hpp"
#include"../comm/httplib.h"
// #include"oj_model.hpp"
#include"oj_model2.hpp"
#include"oj_view.hpp"


namespace ns_control
{
    using namespace std;
    using namespace ns_log;
    using namespace ns_util;
    using namespace ns_model;
    using namespace ns_view;
    using namespace httplib;

    class Machine
    {
    public:
        string ip;      //编译服务的ip
        int port;  //编译服务的port
        uint64_t load;  //编译服务的负载
        mutex *mtx;     //c++中的mutex禁止拷贝，使用湿疹
    
    public:
        Machine()
            :ip(""), port(0), load(0), mtx(nullptr)
        {}

        ~Machine()
        {}

        void IncLoad()
        {
            if(mtx) mtx->lock();
            ++load;
            if(mtx) mtx->unlock();
        }

        void DecLoad()
        {
            if(mtx) mtx->lock();
            --load;
            if(mtx) mtx->unlock();
        }

        void ResetLoad()
        {
            //每次让主机离线都需要清空负载
            if(mtx) mtx->lock();
            load = 0;
            if(mtx) mtx->unlock();
        }
        //获取主机负载，只是为了统一接口
        uint64_t Load()
        {
            uint64_t _load = 0;
            if(mtx) mtx->lock();
            _load = load;
            if(mtx) mtx->unlock();
            return _load;
        }

    };

    const string service_machine = "./conf/service_machine.conf";
    //负载均衡模块
    class LoadBalance
    {
    private:
        //可以给我们提供编译服务的所有主机
        //每一台主机都有自己的下标，充当当前主机的id
        vector<Machine> machines;
        //所有在线主机的id
        vector<int> online;
        //所有离线主机的id
        vector<int> offline;
        //保证LoadBalance中数据安全
        mutex mtx;
    public:
        LoadBalance()
        {
            assert(LoadConf(service_machine));
            LOG(INFO) << "加载 " << service_machine << " 成功" << "\n";
        }

        ~LoadBalance()
        {}

        bool LoadConf(const string& machine_conf)
        {
            ifstream in(machine_conf);
            if(!in.is_open())
            {
                LOG(FATAL) << "加载" << machine_conf << "失败" << "\n";
                return false;
            }
            //按行读取文件内容
            string line;
            while(getline(in,line))
            {
                vector<string> tokens;
                StringUtil::SplitString(line,&tokens,":");
                if(tokens.size() != 2)
                {
                    LOG(WARNING) << "切分" << line << "失败" << "\n";
                    continue;
                }

                Machine m;
                m.ip = tokens[0];
                m.port = stoi(tokens[1]);
                m.load = 0;
                m.mtx = new mutex();

                //假如到machines中
                online.push_back(machines.size());
                machines.push_back(m);
            }

            in.close();
            return true;
        }
        
        //id：输出型参数，machine的id
        //m：输出型参数，哪一个machine
        bool SmartChoice(int* id, Machine** m)
        {
            // 1. 使用选择好的主机(更新该主机的负载)
            // 2. 我们需要可能离线该主机
            mtx.lock();
            //负载均衡算法
            //1.随机数+hash
            //2.轮询 + hash(使用)
            int online_num = online.size();
            if(online_num == 0)
            {
                mtx.unlock();
                LOG(FATAL) << "所有后端编译主机已经离线，请处理" << "\n";
                return false;
            }

            *id = online[0];
            *m = &machines[online[0]];
            uint64_t min_load = machines[online[0]].Load();
            for(int i = 0; i < online_num; i++)
            {
                uint64_t curr_load = machines[online[i]].Load();
                if(min_load > curr_load)
                {
                    min_load = curr_load;
                    *id = online[i];
                    *m = &machines[online[i]];
                }
            }

            mtx.unlock();
            return true;
        }

        bool OnlineMachine()
        {
            //我们统一上线
            //实际就是将离线数组中的所有数据移动到在线数组中
            mtx.lock();
            online.insert(online.end(), offline.begin(), offline.end());
            offline.erase(offline.begin(), offline.end());
            mtx.unlock();

            LOG(INFO) << "所有主机已经上线" << "\n";
        }

        bool OfflineMachine(int which)
        {
            mtx.lock();
            for(auto iter = online.begin(); iter != online.end(); iter++)
            {
                if(which == *iter)
                {
                    machines[which].ResetLoad();
                    //找到离线主机
                    online.erase(iter);
                    offline.push_back(which);
                    break;//因为break的存在，所以迭代器失效的问题我们不需要考虑
                }
            }

            mtx.unlock();
        }

        void ShowMachines()
        {
            mtx.lock();
            cout << "当前在线主机列表: ";
            for(auto& iter: online)
            {
                cout << iter << " ";
            }
            cout << endl;

            cout << "当前离线主机列表: ";
            for(auto& iter: offline)
            {
                cout << iter << " ";
            }
            cout << endl;
            mtx.unlock();
        }
    };


    //核心业务逻辑的控制器
    class Control
    {
    private: 
        Model model_;//提供后台数据
        View view_;  //网页渲染功能
        LoadBalance load_balance_; //负载均衡
    public:
        Control()
        {}

        ~Control()
        {}

        void RecoveryMachine()
        {
            load_balance_.OnlineMachine();
        }

        bool AllQuestions(string *html)
        {
            bool ret = true;
            vector<struct Question> all;
            if(model_.GetAllQuestions(&all))
            {
                //将题目变成有序
                sort(all.begin(), all.end(),[](const struct Question& q1, const struct Question& q2){
                    return stoi(q1.number) < stoi(q2.number);
                });

                //获取题目信息成功，将所有题目构建成网页
                view_.AllExpandHtml(all,html);
            }
            else
            {
                *html = "获取题目失败，形成题目列表失败";
                ret = false;
            }

            return ret;
        }

        bool Question(const string& number, string* html)
        {
            bool ret = true;
            struct Question q;
            if(model_.GetOneQuestion(number,&q))
            {
                //获取指定题目信息成功，将指定题目构建成网页
                view_.OneExpandHtml(q,html);
            }
            else
            {
                *html = "获取指定题目 " + number + "失败";
                ret = false;
            }

            return ret;
        }

        //in_json中包含code, input
        void Judge(const string& number, const string& in_json, string* out_json)
        {
            // LOG(DEBUG) << in_json << "\nnumber" << number << "\n";
            // 0.根据题目编号，拿到对应题目细节
            struct Question q;
            model_.GetOneQuestion(number,&q);

            // 1.in_json进行反序列化，得到题目的id，在得到用户提交的源代码，input
            Json::Value in_value;
            Json::Reader reader;
            reader.parse(in_json, in_value);
            string code = in_value["code"].asString();

            // 2.重新拼接用户代码+测试用例代码，形成新的代码
            Json::Value compile_value;
            compile_value["input"] = in_value["input"].asString();
            compile_value["code"] = code + "\n" + q.tail;
            compile_value["cpu_limit"] = q.cpu_limit;
            compile_value["mem_limit"] = q.mem_limit;

            Json::FastWriter writer;
            string compile_string = writer.write(compile_value);

            // 3.选择负载最低的主机（差错处理）
            // 规则: 一直选择，直到主机可用，否则，就是全部挂掉
            while(true)
            {
                int id = 0;
                Machine* m;
                if(!load_balance_.SmartChoice(&id, &m))
                {
                    break;
                }
                
                // 4.然后发起http请求，得到结果
                Client cli(m->ip, m->port);
                m->IncLoad();
                LOG(INFO) << "选择主机成功, 主机id: " << id << " 详情: " << m->ip << ":" << m->port << " 当前主机的负载是：" << m->Load() << "\n";
                if(auto res = cli.Post("/compile_and_run", compile_string, "application/json;charset=utf-8"))
                {
                    // 5.将结果赋值给out_json（必须在状态码为200情况下赋值，否则返回的值还是错误的)
                    if(res->status == 200)
                    {
                        *out_json = res->body;
                        m->DecLoad();
                        LOG(INFO) << "请求编译和运行服务成功..." << "\n";
                        break;
                    }
                    m->DecLoad();
                }
                else
                {
                    LOG(ERROR) << "当前请求的主机id: " << id << " 详情: "<< m->ip << ":" << m->port << " 可能已经离线" << "\n";
                    load_balance_.OfflineMachine(id);
                    load_balance_.ShowMachines();
                }

            }

            
            
        }
    };

}